package com.heiye.blog.oss.biz.strategy.impl;

import com.aliyun.oss.OSS;
import com.heiye.blog.framework.common.exception.BizException;
import com.heiye.blog.oss.api.model.dto.AudioStreamUploadDTO;
import com.heiye.blog.oss.biz.config.AliyunOSSProperties;
import com.heiye.blog.oss.biz.enums.FileStorageTypeEnum;
import com.heiye.blog.oss.biz.enums.ResponseCodeEnum;
import com.heiye.blog.oss.biz.strategy.FileStrategy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author: heiye
 * @date: 2024/11/21 下午1:33
 * @version: v1.0.0
 * @description: TODO
 */
@Slf4j
@Component
public class AliyunOSSFileStrategy implements FileStrategy {

    @Resource
    private AliyunOSSProperties aliyunOSSProperties;

    @Resource
    private OSS ossClient;

    /**
     * 获取策略类型枚举
     *
     * @return
     */
    @Override
    public FileStorageTypeEnum getStrategyTypeEnum() {
        return FileStorageTypeEnum.ALIYUN_OSS;
    }

    /**
     * 音频文件流式上传
     *
     * @param audioStreamUploadDTO
     * @return
     */
    @Override
    public String audioStreamUpload(AudioStreamUploadDTO audioStreamUploadDTO) {
        log.info("## 音频文件流式上传至阿里云 OSS ...");

        // 判断文件是否为空
        if (Objects.isNull(audioStreamUploadDTO) || StringUtils.isEmpty(audioStreamUploadDTO.getAudioType())) {
            log.error("==> 音频文件流式上传异常：音频文件为空 ...");
            throw new BizException(ResponseCodeEnum.FILE_SIZE_EMPTY);
        }

        // 生成存储对象的名称（将 UUID 字符串中的 - 替换成空字符串）
        String key = UUID.randomUUID().toString().replace("-", "");
        // 获取文件的后缀，如 wav
        String suffix = audioStreamUploadDTO.getAudioType();
        // 获取音频文件存储路径
        String audioPath = aliyunOSSProperties.getAudioPath();
        // 获取存储桶名称
        String bucketName = aliyunOSSProperties.getBucketName();

        // 拼接上文件后缀，即为要存储的文件名
        String objectName = String.format("%s/%s.%s", audioPath, key, suffix);

        log.info("==> 开始音频文件流式上传至阿里云 OSS, ObjectName: {}", objectName);

        // 上传文件到阿里云 OSS
        ossClient.putObject(bucketName, objectName, audioStreamUploadDTO.getInputStream());

        // 返回文件的访问链接
        String url = String.format("https://%s.%s/%s", bucketName, aliyunOSSProperties.getEndpoint(), objectName);
        log.info("==> 音频文件流式上传至阿里云 OSS 成功，访问路径: {}", url);

        return url;
    }
}
